//导入数据库操作模块
const db = require('../db/index')

//导入加密密码模块
const bcrypt = require('bcryptjs')

//导入生成token字符串的包
const jwt = require('jsonwebtoken')
//导入全局配置文件
const config = require('../config')
//封装身份状态函数
function status(status) {
  switch (status) {
    case '学生':
      return 'student'
    case '教师':
      return 'teacher'
    case '管理员':
      return 'administrator'
  }
}
exports.register = (req, res) => {
  const userinfo = req.body
  const identity = status(userinfo.status)
  const sql = `select * from ${identity} where id=?`
  db.query(sql, userinfo.id, (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (results.length) {
      return res.cc('账号已被占用，请更换其他账号！')
    }
    userinfo.password = bcrypt.hashSync('111111', 12)
    delete userinfo.status
    const sqlStr = `insert into ${identity} set ?`
    db.query(sqlStr, { ...userinfo }, (err, results) => {
      if (err) {
        return res.cc(err)
      }
      if (results.affectedRows !== 1) {
        return res.cc('注册用户失败，请稍后再试！')
      }
      res.cc('注册成功！', 0)
    })
  })
}

exports.login = (req, res) => {
  const userinfo = req.body
  const identity = status(userinfo.status)
  const sql = `select * from ${identity} where id=?`
  db.query(sql, userinfo.id, (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (!results.length) {
      return res.cc('登录失败！')
    }
    const flag = bcrypt.compareSync(userinfo.password, results[0].password)
    if (!flag) {
      return res.cc('登录失败！')
    }
    const user = { ...results[0], password: '', identity: userinfo.status }
    const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })

    res.send({
      status: 0,
      message: '登录成功！',
      token: 'Bearer ' + tokenStr
    })
  })
}